<?php

use PHPUnit\Samples\Money\Money;
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class b2c_ctl_site_order extends b2c_frontpage{

    var $noCache = true;

    public function __construct(&$app){
        parent::__construct($app);
        #$shopname = app::get('site')->getConf('site.name');
        #if(isset($sysconfig)){
        #    $this->title = app::get('b2c')->_('订单').'_'.$shopname;
        #    $this->keywords = app::get('b2c')->_('订单_').'_'.$shopname;
        #    $this->description = app::get('b2c')->_('订单_').'_'.$shopname;
        #}
        $this->header .= '<meta name="robots" content="noindex,noarchive,nofollow" />';
        $this->_response->set_header('Cache-Control', 'no-store');
		
        $this->title=app::get('b2c')->_('订单中心');
        $this->objMath = kernel::single("ectools_math");
    }

    public function create()
    {

        /**
         * 取到扩展参数,用来判断是否是团购立即购买，团购则不判断登录（无注册购买情况下）
         */
        $arr_args = func_get_args();
        $arr_args = array(
            'get' => $arr_args,
            'post' => $_POST,
        );
        $groupbuy = (array)json_decode($arr_args['post']['extends_args']);
        // 判断顾客登录方式.
        #$login_type = $this->app->getConf('site.login_type');
        $arrMember = kernel::single('b2c_user_object')->get_current_member(); //member_id,uname
        // checkout url
        $this->begin(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout'));
        $db = kernel::database();
        $transaction_status = $db->beginTransaction();
        $this->mCart = $this->app->model('cart');
        if(isset($_POST['isfastbuy']) && $_POST['isfastbuy']){
            $is_fastbuy = 'true';
            $fastbuy_filter['is_fastbuy'] = $is_fastbuy;
        }else{
            $is_fastbuy = false;
            $fastbuy_filter = true;
        }
        $aCart = $this->mCart->get_objects($fastbuy_filter);

        //当有活动时，在生成订单前做一个当前购买数量与实际库存的判断
        if( isset($aCart['cart_status'] )){

            $this->end(false,app::get('b2c')->_($aCart['cart_error_html']),$this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'index')),true,true);

        }
        // 校验购物车是否为空
        if ($this->mCart->is_empty($aCart))
        {
            $db->rollback();
            $this->end(false,app::get('b2c')->_('操作失败，购物车为空！'),$this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'index')),true,true);
        }
        // 校验购物车有没有发生变化
        $md5_cart_info = $_POST['md5_cart_info'];

        if (!defined("STRESS_TESTING") && $md5_cart_info != kernel::single("b2c_cart_objects")->md5_cart_objects($is_fastbuy))
        {
            $db->rollback();
            $this->end(false,app::get('b2c')->_('购物车内容发生变化，请重新结算！'),$this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')),true,true);
        }

        $msg = "";
        //判断团购限制数量
        $starbuy_special_count = kernel::service('special_count_member_buy');
        if($starbuy_special_count != null){
            $starbuy_tmp = $aCart['object']['goods'];
            foreach($starbuy_tmp as $starbuy_goods)
            {
                foreach($starbuy_goods['obj_items']['products'] as $starbuy_product)
                {
                    $fmt_check_products[$starbuy_product['product_id']] = $starbuy_goods['quantity'];
                }
            }
            if($fmt_check_products != null){
                $special_goods = $starbuy_special_count->get_special_products($fmt_check_products);
                if($special_goods != null)
                {
                    foreach($special_goods as $tmp_special_goods)
                    {
                        if($starbuy_special_count->check_count($arrMember['member_id'],$tmp_special_goods['product_id'],$fmt_check_products[$tmp_special_goods['product_id']]) == false){
                            $db->rollback();
                            $this->end(false,app::get('b2c')->_('您的购物车中有商品数量超出了可购买数量，请检查购物车。'), null,true,true);
                        }
                        $starbuy_special_count->add_count($arrMember['member_id'], $tmp_special_goods['product_id'], $fmt_check_products[$tmp_special_goods['product_id']]);
                    }
                }
            }
        }
        if(!$_POST['trans_mode']){
            $db->rollback();
            $msg .= app::get('b2c')->_("请先确认运输方式")."<br />";
            $this->end(false, $msg, '',true,true);
        }else{
            $_POST['delivery']['trans_mode'] = $_POST['trans_mode'];
            if( is_numeric($_POST['trans_mode']) ){
                $_POST['styke'] = 'Самовывоз';
            }else{
                $_POST['styke'] = $_POST['trans_mode']; //提货方式 by yyj 2015/12/14
            }
            unset($_POST['trans_mode']);
        }
        if($_POST['delivery']['trans_mode']!='Самовывоз'){//自提
            if(!$_POST['ship_id']){
                $db->rollback();
                $msg .= app::get('b2c')->_("请确认运输公司")."<br />";
                $this->end(false, $msg, '',true,true);
            }else{
                $shipping = $_POST['ship_id'];
                unset($_POST['ship_company']);
                $_POST['delivery']['shipping_id'] = $shipping;
            }
            if(!$_POST['addr']){
                $db->rollback();
                $msg .= app::get('b2c')->_("请先确认收货地址")."<br />";
                $this->end(false, $msg,'',true,true);
            }else{
                $addr=json_decode($_POST['addr'],1);
                unset($_POST['addr']);
                $ship_area_name = app::get('ectools')->model('regions')->change_regions_data($addr['area']);
                $_POST['delivery']['addr_id'] = $addr['addr_id'];
                $_POST['delivery']['ship_area'] = $addr['area'];
                $_POST['delivery']['ship_addr'] = $ship_area_name.' '.$addr['addr'];
                $_POST['addr_id'] = $addr['addr_id']; //收货地址ID by yyj 2015/12/14
            }
            if(!$_POST['receiver']){
                $db->rollback();
                $msg .= app::get('b2c')->_("请先确认收货人")."<br />";
                $this->end(false, $msg, '',true,true);
            }else{
                $receiver = json_decode($_POST['receiver'],1);
                unset($_POST['receiver']);
                if(mb_strlen($receiver['name'],'utf-8')>150){
                    $msg .= "Максимальное количество букв: 150";
                    $this->end(false, $msg, '',true,true);
                }
                $_POST['delivery']['ship_name'] = $receiver['name'];
                if($receiver['mobile']){
                    $_POST['delivery']['ship_tel'] = $receiver['phone_setting'].' '.$receiver['mobile'];
                }else{
                    $_POST['delivery']['ship_tel'] = $receiver['tel'];
                }
                $_POST['consignee_id'] = $receiver['consignee_id']; //收货人ID by yyj 2015/12/14
            }

        }
        if(!$_POST['company']){
            $db->rollback();
            $msg .= app::get('b2c')->_("请先确认付款公司")."<br />";
            $this->end(false, $msg, '',true,true);
        }else{
            $pay_com = json_decode($_POST['company'],1);
            unset($_POST['company']);
            $_POST['payment']['pay_com_id'] = $pay_com['company_id'];
            $_POST['payment']['pay_com_name'] = $pay_com['name'];
            if($pay_com['c_type']=='3'){
                $_POST['payment']['pay_com_inn'] = $pay_com['inn_p'];
            }else{
                $_POST['payment']['pay_com_inn'] = $pay_com['inn'];
            }

            if($pay_com['c_type'] === '1')
            {
                $_POST['payment']['company_c_type'] = app::get('b2c')->_("ЗАО");
            }
            else if($pay_com['c_type'] === '2')
            {
                $_POST['payment']['company_c_type'] = app::get('b2c')->_("ИП");
            }
            else if($pay_com['c_type'] === '3')
            {
                $_POST['payment']['company_c_type'] = app::get('b2c')->_("个人");
            }
            else
            {
                $_POST['payment']['company_c_type'] = app::get('b2c')->_("ООО");
            }
        }

        //-------------总金额不能少于1000---------
//        $total_amounts = $this->objMath->number_minus(array($aCart["subtotal"], $aCart['discount_amount']));
//        if($total_amounts<10000){
//            $db->rollback();
//            $msg .= app::get('b2c')->_("Минимальная сумма закупки 10000руб")."<br />";
//            $this->end(false, $msg, '',true,true);
//        }
        /*end*/
        if($_POST['point']['score']){
            $_POST['payment']['dis_point'] = $_POST['point']['score'];
        }
        $obj_dlytype = $this->app->model('dlytype');
        if ($_POST['payment']['pay_app_id'] == '-1')
        {
            $arr_dlytype = $obj_dlytype->dump($_POST['delivery']['shipping_id'], '*');
            if ($arr_dlytype['has_cod'] == 'false')
            {
                $this->end(false, $this->app->_("ship_method_consistent_error"),'',true,true);
            }
        }
        $obj_filter = kernel::single('b2c_site_filter');
        $_POST = $obj_filter->check_input($_POST);
        $order = $this->app->model('orders');
        if( $order->gen_id() ) {
            $_POST['order_id'] = $order_id = $order->gen_id();
        }else{
            $order_msg = app::get('b2c')->_("Система перегружена, пожалуйста, попробуйте зайти позже.");
            $this->end(false, $order_msg, '',true,true);
        }

        $_POST['member_id'] = $arrMember['member_id'] ? $arrMember['member_id'] : 0;
        $order_data = array();
        $obj_order_create = kernel::single("b2c_order_create");
        //----------liuyulei 是否是预售商品-------------
        $is_pre_sale = 0;
        if(!empty($_COOKIE['cart_objects_checked'])) {
            $cart_objects_checked = unserialize($_COOKIE['cart_objects_checked']);
            foreach ($aCart['object']['goods'] as $_good) {
                if ($_good['is_pre_sale'] && in_array($_good['obj_ident'],$cart_objects_checked)) {
                    $is_pre_sale += 1;
                }
                if($is_pre_sale>0){
                    break;
                }
            }
        }
        if ($is_pre_sale > 0) {
            $_POST['pre_order'] =  true;
            $_POST['pre_number'] =  $order_pre_id = $order->gen_presale_id();
        } else {
            $_POST['pre_order'] =  false;
        }
        //----------liuyulei 是否是预售商品 end------------
        // 加入订单能否生成的判断
        $obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
        if ($obj_checkorder)
        {
            if (!$obj_checkorder->check_create($aCart, $_POST['delivery']['ship_area'], $message))
                $this->end(false, $message);
        }
        $order_data = $obj_order_create->generate($_POST,'',$msg,$aCart);


        $obj_checkproducts = kernel::servicelist('b2c_order_check_products');
        if ($obj_checkproducts)
        {
            foreach($obj_checkproducts as $obj_check){
                if (!$obj_check->check_products($order_data, $messages))
                    $this->end(false, $messages);
            }
        }
        if (!$order_data || !$order_data['order_objects'])
        {
            $db->rollback();
            $this->end(false, $msg, $this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')),true,true);
        }

        //给订单表加上预售标识
        foreach ($order_data['order_objects'] as $arr_objects)
        {
            if ($arr_objects['order_items'])
            {
                foreach ($arr_objects['order_items'] as $arr_items)
                {
                    if ($arr_objects['obj_type'] == 'goods')
                    {
                        if ($arr_items['item_type'] == 'product')
                            $product_id[]=$arr_items['products']['product_id'];
                    }
                }
            }
        }
        $prepare_order = kernel::service('prepare_order');
        if($prepare_order)
        {
            $promotion_type = $prepare_order->get_promotion_type($product_id);
        }
        //echo '<pre>';print_r($promotion_type);exit();
        if($promotion_type['promotion_type'])
        {
            $order_data['promotion_type']=$promotion_type['promotion_type'];
        }
        //----------liuyulei 是否是预售商品-------------
        if ($is_pre_sale > 0) {
            $order_data['pre_order'] =  true;
            $order_data['pre_number'] =  $order_pre_id;
        } else {
            $order_data['pre_order'] =  false;
        }
        //----------liuyulei 是否是预售商品 end------------
        //----------liuyulei 是否需要确认库存------------
        foreach($order_data['order_objects'] as $_bk=>$_bv) {
            foreach($_bv['order_items'] as $_bkey=>$_bval) {
                $order_goods[] = $_bval['goods_id'] ;
            }
        }
        $sto_confirm = $this->app->model('goods')->getRow('goods_id', array('sto_confirm'=>'Y','goods_id|in' => $order_goods));
        if(!$sto_confirm){
            $order_data['confirm_time'] = time();
        }
        //----------liuyulei 是否需要确认库存 end------------


        //保存主订单
        $result = $obj_order_create->save($order_data, $msg);
        //------liuyulei 更新批次表------
//        $order_items = $this->app->model('order_items');
//        foreach($order_data['order_objects'] as $_bk=>$_bv) {
//            foreach($_bv['order_items'] as $_bkey=>$_bval) {
//                $goods_ib = 'goods_'.$_bval['goods_id'].'_'.$_bval['products']['product_id'];
//                if($aCart['promotion']['goods'][$goods_ib]){
//                    foreach($aCart['promotion']['goods'][$goods_ib] as $_k=>$_v){
//                        $discount_amount = round($_v['discount_amount']);
//                        $order_items->update( array('goods_discount'=>$discount_amount), array('item_id'=>$_bval['item_id']) );
//                    }
//                }
//            }
//        }
        //------liuyulei 更新批次表 end------

        //同时在预售订单表添加条数据243-251行
        if($promotion_type['promotion_type']=='prepare')
        {   $data=array(
            'order_id'=>$order_data['order_id'],
            'member_id'=>$arrMember['member_id'] ? $arrMember['member_id'] : 0,
            'mobile'=>$order_data['consignee']['mobile'],
            'email'=>$arrMember['email'],
            'product_id'=>$order_data['order_objects'][0]['order_items'][0]['products']['product_id'],
            'name'=>$order_data['order_objects'][0]['order_items'][0]['name'],
        );
            kernel::service('prepare_order')->sava_prepare_order($data);
        }

        if ($result)
        {

            // 发票高级配置埋点
            foreach( kernel::servicelist('invoice_setting') as $services ) {
                if ( is_object($services) ) {
                    if ( method_exists($services, 'saveInvoiceData') ) {
                        $services->saveInvoiceData($_POST['order_id'],$_POST['payment']);
                    }
                }
            }

            // 与中心交互
            $is_need_rpc = false;
            $obj_rpc_obj_rpc_request_service = kernel::servicelist('b2c.rpc_notify_request');
            foreach ($obj_rpc_obj_rpc_request_service as $obj)
            {
                if ($obj && method_exists($obj, 'rpc_judge_send'))
                {
                    if ($obj instanceof b2c_api_rpc_notify_interface)
                        $is_need_rpc = $obj->rpc_judge_send($order_data);
                }

                if ($is_need_rpc) break;
            }

            if ($is_need_rpc)
            {
                /*
                  $obj_rpc_request_service = kernel::service('b2c.rpc.send.request');

                  if ($obj_rpc_request_service && method_exists($obj_rpc_request_service, 'rpc_caller_request'))
                  {
                      if ($obj_rpc_request_service instanceof b2c_api_rpc_request_interface)
                          $obj_rpc_request_service->rpc_caller_request($order_data,'create');
                  }
                  else
                  {
                      $obj_order_create->rpc_caller_request($order_data);
                      }*/
                //新的版本控制api
                $obj_apiv = kernel::single('b2c_apiv_exchanges_request');
                $obj_apiv->rpc_caller_request($order_data, 'ordercreate');
            }
        }

        // 取到日志模块
        if ($arrMember['member_id'])
        {
            $obj_members = $this->app->model('members');
            $arrPams['pam_account']['login_name'] = $arrMember['uname'];
        }

        // remark create
        $obj_order_create = kernel::single("b2c_order_remark");
        $arr_remark = array(
            'order_bn' => $order_id,
            'mark_text' => $_POST['memo'],
            'op_name' => (!$arrMember['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
            'mark_type' => 'b0',
        );

        $log_text = "";
        if ($result)
        {
            $log_text[] = array(
                'txt_key'=>'订单创建成功！',
                'data'=>$order_data,
            );
            $log_text = serialize($log_text);
        }
        else
        {
            $log_text[] = array(
                'txt_key'=>'订单创建失败！',
                'data'=>$order_data,
            );
            $log_text = serialize($log_text);
        }
        $orderLog = $this->app->model("order_log");
        $sdf_order_log = array(
            'rel_id' => $order_id,
            'op_id' => $arrMember['member_id'],
            'op_name' => (!$arrMember['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
            'alttime' => time(),
            'bill_type' => 'order',
            'behavior' => 'creates',
            'result' => 'SUCCESS',
            'log_text' => $log_text,
        );

        $log_id = $orderLog->save($sdf_order_log);
        $arr_updates = array();

        if ($result)
        {
            foreach(kernel::servicelist('b2c_save_post_om') as $object)
            {
                $object->set_arr($order_id, 'order');
            }

            // 设定优惠券不可以使用
            if (isset($aCart['object']['coupon']) && $aCart['object']['coupon'])
            {
                $obj_coupon = kernel::single("b2c_coupon_mem");
                foreach ($aCart['object']['coupon'] as $coupons)
                {
                    if($coupons['used'])
                        $obj_coupon->use_c($coupons['coupon'], $arrMember['member_id']);
                }
            }

            // 订单成功后清除购物车的的信息
            //edit yhy 根据勾选清除购物车数据,删除cookie
            $this->cart_model = $this->app->model('cart_objects');
            $this->cart_model->remove_object('',null,$mag,$is_fastbuy);
            $this->set_cookie('cart_objects_checked','',time()-3600);
            $this->set_cookie('cart_obj_checked','',time()-3600);
            //end
            // 生成cookie有效性的验证信息
            setcookie('ST_ShopEx-Order-Buy', md5($this->app->getConf('certificate.token').$order_id));
            setcookie("purchase[addr][usable]", "", time() - 3600, kernel::base_url().'/');
            setcookie("purchase[shipping]", "", time() - 3600, kernel::base_url().'/');
            setcookie("purchase[payment]", "", time() - 3600, kernel::base_url().'/');
            setcookie("checkout_b2c_goods_buy_info", "", time() - 3600, kernel::base_url().'/');

            // 得到物流公司名称
            if ($order_data['order_objects'])
            {
                $itemNum = 0;
                $good_id = "";
                $goods_name = "";
                $goods_num = "";
                $goods_price = "";
                $goods_url = "";
                $thumbnail_pic = "";
                $goods_info = "";
				
				$goods_info = array();
				$goods_counter = 0;
				$goods_total_without_discounts = 0;
                foreach ($order_data['order_objects'] as $arr_objects)
                {
                    if ($arr_objects['order_items'])
                    {
                        if ($arr_objects['obj_type'] == 'goods')
                        {
                            $obj_goods = $this->app->model('goods');
                            $good_id = $arr_objects['order_items'][0]['goods_id'];
                            $obj_goods->updateRank($good_id, 'buy_count',$arr_objects['order_items'][0]['quantity']);
                            $arr_goods = $obj_goods->parent_getList('image_default_id',array('goods_id'=>$good_id));
                            $arr_goods = $arr_goods[0];

                        }
                        foreach ($arr_objects['order_items'] as $arr_items)
                        {
                            $itemNum = $this->objMath->number_plus(array($itemNum, $arr_items['quantity']));
                            if ($arr_objects['obj_type'] == 'goods')
                            {
                                if ($arr_items['item_type'] == 'product')
                                {
                                    $goods_name .= $arr_items['name'] . ($arr_items['products']['spec_info'] ? '(' . $arr_items['products']['spec_info'] . ')' : '') . '(' . intval($arr_items['quantity']) . ')' . '<br/>';
                                    $goods_num  += intval($arr_items['quantity']);
                                    $goods_price.= round($arr_items['price']).'руб'. '<br/>';
                                    $goods_url  .= '<a href=" ' .kernel::base_url(1).kernel::url_prefix().$this->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$arr_items['products']['product_id'])). '></a><br/>';
                                    $thumbnail_pic .= '<img src="' .base_storager::image_path($arr_goods['image_default_id']). '"/><br/>';
                                    /*$goods_info .= '<a href=" ' . kernel::base_url(1).kernel::url_prefix().$this->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$arr_items['products']['product_id'])) . '">'
                                        . '<img src="' . base_storager::image_path($arr_goods['image_default_id']) .'"/></a>'
                                        . '<a href=" ' . kernel::base_url(1).kernel::url_prefix().$this->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$arr_items['products']['product_id'])) . '">'
                                        . $arr_items['name'] . ($arr_items['products']['spec_info'] ? '(' . $arr_items['products']['spec_info']
                                            . ')' : '') . '(' . intval($arr_items['quantity']) . ')'.'</a>&nbsp;&nbsp;&nbsp;&nbsp;'
                                        .app::get('b2c')->_('商品数量'). ':&nbsp;' . intval($arr_items['quantity']) . '&nbsp;&nbsp;&nbsp;&nbsp;'
                                        .app::get('b2c')->_('商品价格'). ':&nbsp;' .round($arr_items['price']).'руб'
                                        .'<br/>';*/
									$goods_info[$goods_counter]['id'] = $arr_items['products']['product_id'];	
									$goods_info[$goods_counter]['vendor_code'] = $arr_items['bn'];	
									$goods_info[$goods_counter]['url'] = kernel::base_url(1).kernel::url_prefix().$this->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$arr_items['products']['product_id']));	
									$goods_info[$goods_counter]['name'] = $arr_items['name'];	
									$goods_info[$goods_counter]['thumbnail'] = base_storager::image_path($arr_goods['image_default_id']);	
									$g_count = intval($arr_items['quantity']);
									$g_price = floor($arr_items['price']);
									$g_summ = $g_count*$g_price;
									$goods_info[$goods_counter]['count'] = $g_count;	
									$goods_info[$goods_counter]['price'] = $g_price;
									$goods_info[$goods_counter]['summ'] = $g_summ;
									$goods_total_without_discounts += $g_summ;
                                }
                            }
                        }
                    }
					$goods_counter++;
                }
				$total_discount = $goods_total_without_discounts - $order_data['total_amount'];
				
                $arr_dlytype = $obj_dlytype->dump($order_data['shipping']['shipping_id'], 'dt_name');
                $arr_updates = array(
                    'order_id' => $order_id,
                    'total_amount' => $order_data['total_amount'],
                    'shipping_id' => $arr_dlytype['dt_name'],
                    'ship_mobile' => $order_data['consignee']['mobile'],
                    'ship_tel' => $order_data['consignee']['telephone'],
                    'ship_addr' => $order_data['consignee']['addr'],
                    'ship_email' => $order_data['consignee']['email'] ? $order_data['consignee']['email'] : '',
                    'ship_zip' => $order_data['consignee']['zip'],
                    'ship_name' => $order_data['consignee']['name'],
                    'member_id' => $order_data['member_id'] ? $order_data['member_id'] : 0,
                    'uname' => (!$order_data['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
                    'itemnum' => count($order_data['order_objects']),
                    'goods_id' => $good_id,
                    'goods_url' => $goods_url,
                    'thumbnail_pic' => $thumbnail_pic,
                    'goods_name' => $goods_name,
                    'ship_status' => '',
                    'pay_status' => 'Nopay',
                    'is_frontend' => true,
                    'goods_num' => $goods_num,//商品数量
                    'goods_price' => $goods_price,//销售价
                    'goods_info' => $goods_info,//商品全部信息
					'total_discount' => $total_discount
                );
                //echo '<pre>';
                //print_r($arr_updates);
                //echo '</pre>';exit();
                $cancelorder_obj = kernel::servicelist("cancelorder");
                foreach($cancelorder_obj as $obj_cancelorder){
                    $obj_cancelorder->cancel($order_id,$msg);
                }

            }

            $db->commit($transaction_status);

            if ($order_data['order_objects'])
            {
//                $order->fireEvent('create', $arr_updates, $order_data['member_id']);
//                $myself_email = 'order@qifa.ru';
//                $messenger_mod = app::get('b2c')->model('member_messenger')
//                    ->actionSend('orders-create',$arr_updates,null,$myself_email);
            }

            /** 订单创建结束后执行的方法 **/
            $odr_create_service = kernel::servicelist('b2c_order.create');
            $arr_order_create_after = array();
            if ($odr_create_service)
            {
                foreach ($odr_create_service as $odr_ser)
                {
                    if(!is_object($odr_ser)) continue;

                    if( method_exists($odr_ser,'get_order') )
                        $index = $odr_ser->get_order();
                    else $index = 10;

                    while(true) {
                        if( !isset($arr_order_create_after[$index]) )break;
                        $index++;
                    }
                    $arr_order_create_after[$index] = $odr_ser;
                }
            }
            ksort($arr_order_create_after);
            if ($arr_order_create_after)
            {
                foreach ($arr_order_create_after as $obj)
                {
                    $obj->generate($order_data);
                }
            }
            /** end **/
        }
        else
        {
            $db->rollback();
        }

        //生成分单 yhy
        if($result){

            $obj_order_create=kernel::single('b2c_order_create');
            $bCart=$aCart;
            $goodsMdl = $this->app->model('goods');
            $ectools_math=kernel::single('ectools_math');
            foreach($bCart['object']['goods'] as $gkey=>$gvalue){
                $goods_id=$gvalue['params']['goods_id'];
                $goodsinfo=$goodsMdl->getList('business_id',array('goods_id'=>$goods_id));
                $business_id=$goodsinfo[0]['business_id'];
                $bCart['object']['goods'][$gkey]['business_id']=$business_id;
            }
            $cart_goods=$bCart['object']['goods'];
            $j=1;
            $busi=$cart_goods[0]['business_id'];
            foreach($cart_goods as $k=>$v){
                if($busi!=$v['business_id']){
                    $j++;
                }
            }
            $busi_id=$bCart['object']['goods'][0]['business_id'];
            $cartObj[$business_id]=array();
            for($i=0;$i<$j;$i++){
                foreach($bCart['object']['goods'] as $key=>$value){
                    if($bCart['object']['goods'][$key]['business_id']==$busi_id){
                        $cartObj[$busi_id][]=$bCart['object']['goods'][$key];
                        unset($bCart['object']['goods'][$key]);
                    }
                }
                $cur_cart=current($bCart['object']['goods']);
                $busi_id=$cur_cart['business_id'];
            }
            /*分单的商品数据*/
            foreach($cartObj as $Okey=>$Ovalue){
                $bCart['object']['goods']=$Ovalue;
                $cCart[$Okey]=$bCart;
            }
            foreach($cCart as $dkey=>$dvalue){
                $subtotal=0;
                $subtotal_price=0;
                $subtotal_prefilter_after=0;
                $subtotal_weight=0;
                $subtotal_capacity=0;
                $discount_amount=0;
                $discount_amount_prefilter=0;
                $num=0;
                unset($cCart[$dkey]['goods_min_buy']);
                unset($cCart[$dkey]['promotion']);
                unset($cCart[$dkey]['promotion_solution']);
                foreach($dvalue['object']['goods'] as $ckey=>$cvalue){
                    $subtotal+=$cvalue['subtotal'];
                    $subtotal_price+=$cvalue['subtotal_price'];
                    $subtotal_prefilter_after+=$cvalue['subtotal_prefilter_after'];
                    $subtotal_weight+=$cvalue['subtotal_weight'];
                    $subtotal_capacity+=$cvalue['subtotal_capacity'];
                    $discount_amount+=$cvalue['discount_amount'];
                    $num+=$cvalue['quantity'];
                    $discount_amount_prefilter+=$cvalue['discount_amount_prefilter'];
                    $cCart[$dkey]['items_count']=$cCart[$dkey]['items_count_widgets']=count($dvalue['object']['goods']);
                }
                $cCart[$dkey]['subtotal_price']=$subtotal_price;
                $cCart[$dkey]['subtotal']=$subtotal;
                $cCart[$dkey]['subtotal_weight']=$subtotal_weight;
                $cCart[$dkey]['subtotal_capacity']=$subtotal_capacity;
                $cCart[$dkey]['discount_amount']=$discount_amount;
                $cCart[$dkey]['discount_amount_prefilter']=$discount_amount_prefilter;
                $cCart[$dkey]['subtotal_prefilter_after']=$subtotal_prefilter_after;
                $cCart[$dkey]['items_quantity']=$cCart[$dkey]['items_quantity_widgets']=$num;
                $cCart[$dkey]['discount_amount_order']=0;
            }
            foreach($cCart as $key=>$value){
                $_POST['order_id']=$order->gen_order_id();//子订单号----jyy
                $order_data1[]= $obj_order_create->generate($_POST,'',$msg,$value,false);
            }
            $business_orderMdl=&app::get('b2c')->model('business_orders');
            $goodsMdl=&app::get('b2c')->model('goods');
            foreach($order_data1 as $k=>$v){
                foreach($v['order_objects'] as $orderKey=>$orderValue){
                    $order_data1[$k]['order_objects'][$orderKey]['childOrder_id']=$v['order_id'];
                    $order_data1[$k]['order_objects'][$orderKey]['mainOrder_id']=$order_id;
                    $order_data1[$k]['order_objects'][$orderKey]['business_id']=$v['business_id'];
                    $order_data1[$k]['order_objects'][$orderKey]['buy_price']=$orderValue['order_items'][0]['price'];
                    $order_data1[$k]['order_objects'][$orderKey]['amount']=$orderValue['order_items'][0]['amount'];
                    $order_data1[$k]['order_objects'][$orderKey]['createtime']=time();
                    $image=$goodsMdl->getRow('image_default_id',array('goods_id'=>$orderValue['goods_id']));
                    $order_data1[$k]['order_objects'][$orderKey]['image_default_id']=$image['image_default_id'];
                    $order_data1[$k]['order_objects'][$orderKey]['product_id']=$orderValue['order_items'][0]['products']['product_id'];
                    //判断商品如果不需要确认库存，则status默认为Y@kim
                    if($_POST['pre_order']){
                        //---------liuyulei 预购商品不需要确认库存 start-----------
                        $order_data1[$k]['order_objects'][$orderKey]['state'] = '1';
                        $order_data1[$k]['order_objects'][$orderKey]['confirm_num'] = $orderValue['quantity'];
                        $order_data1[$k]['order_objects'][$orderKey]['has_confirm_num'] = $orderValue['quantity'];
                        //---------liuyulei 预购商品不需要确认库存 end-----------
                    }else {
                        $status = $goodsMdl->getRow('sto_confirm', array('goods_id' => $orderValue['goods_id']));
                        //现修改为只判断商品是否需要确认库存，供应商和品牌不进行判断，goods_confirm为先查找供应商是否需要确认，
                        //再判断品牌是否需要确认，商品是否需要确认库存，依据这三个字段确认最终goods_confirm为Y或N
                        //需要确认库存状态为Y----jyy 2016/10/18-----
                        if ($status['sto_confirm'] == 'Y') {
                            $order_data1[$k]['order_objects'][$orderKey]['state'] = '0';//0未确认
                            $order_data1[$k]['order_objects'][$orderKey]['confirm_num'] = $order_data1[$k]['order_objects'][$orderKey]['order_items'][0]['quantity'];//$orderValue['quantity'];
                            $order_data1[$k]['order_objects'][$orderKey]['has_confirm_num'] = $order_data1[$k]['order_objects'][$orderKey]['order_items'][0]['quantity'];//$orderValue['quantity'];
                            //goods_confirm需要确认库存状态为Y----jyy 2016/10/14-----
                        }
                        else{
                            $order_data1[$k]['order_objects'][$orderKey]['state'] = '1';//1已确认
                            $order_data1[$k]['order_objects'][$orderKey]['confirm_num'] = $order_data1[$k]['order_objects'][$orderKey]['order_items'][0]['quantity'];//$orderValue['quantity'];
                            $order_data1[$k]['order_objects'][$orderKey]['has_confirm_num'] = $order_data1[$k]['order_objects'][$orderKey]['order_items'][0]['quantity'];
                        }
                    }
                }
            }
            foreach($order_data1 as $k=>$v){
                $data=array(
                    'mainOrder_id'=>$order_id,
                    'childOrder_id'=>$v['order_id'],
                    'member_id'=>$v['member_id'],
                    'business_id'=>$v['business_id'],
                    'order_amount'=>$v['cost_item'],
                    'order_num'=>$v['itemnum'],
                    'createtime'=>time(),//分单表内添加时间字段
                    'order_objects'=>$v['order_objects'],
                );

                $return=$business_orderMdl->save($data);
                //判断商品如果不需要确认库存，分单内的状态更改，orders表里的状态也要改@kim
                $b_status = $this->check_b_orders(array('childOrder_id'=>$data['childOrder_id']));
                $business_orderMdl->update(array('status'=>$b_status),array('childOrder_id'=>$data['childOrder_id']));
                $c_status = $this->check_order(array('mainOrder_id'=>$data['mainOrder_id']));
                $orders_ship = $order->getRow('*',array('order_id'=>$order_id));
                $obj_type = app::get('b2c')->model('dlytype');
                $dt_info = $obj_type->dump($orders_ship['shipping_id']);
                if($c_status == 1 || $c_status == 2){
                    //是否有推荐商品或者确认数量与购数量不同
                    $objRg = $this->app->model('business_recommend_goods');
                    if($objRg->count(array('mainOrder_id'=>$data['mainOrder_id'])) || $this->check_item_num(array('mainOrder_id'=>$data['mainOrder_id']))){
                        if($dt_info['cost_confirm'] == 'true'){//运费需要确认
                            $c_status = '1';//待确认运费
                        }else{
                            $c_status = '2';//待付款
                        }
                        $order->update(array('c_status'=>$c_status),array('order_id'=>$data['mainOrder_id']));
                    }
                    else{
                        if($dt_info['cost_confirm'] == 'true'){//运费需要确认
                            $c_status = '1';//待确认运费
                        }else{
                            $c_status = '2';//待付款
                        }
                        $order->update(array('c_status'=>$c_status),array('order_id'=>$data['mainOrder_id']));
                        //供应商库存确认后要给客户发送短信
                        //$orders = $order->dump(array('order_id'=>$data['mainOrder_id']),'member_id');
                        //供应商库存确认后给客户发送短信，内容添加订单总金额，总件数，付款公司----jyy--/2016/10/19
                        //$fire_data = array('order_id'=>$data['mainOrder_id'],
                            //'total_amount'=>$order_data['total_amount'],//订单总金额
                            //'pay_account'=>$order_data['company_name']//付款公司
                        //);
                        //$order->fireEvent('storeconfirmall',$fire_data,$orders['member_id']);
                    }

                }else{
                    $order->update(array('c_status'=>0),array('order_id'=>$data['mainOrder_id']));
                }

                //$fire_data = array('order_id'=>$v['order_id'],'business_id'=>$v['business_id']);
                $fire_data = array('order_id'=>$data['childOrder_id'],'business_id'=>$data['business_id']);
                $order->fireEvent('childcreate',$fire_data,$data['business_id']);
            }
        }
        if ($result)
        {
            $order_num = $order->count(array('member_id' => $order_data['member_id']));
            $obj_mem = $this->app->model('members');
            $obj_mem->update(array('order_num'=>$order_num), array('member_id'=>$order_data['member_id']));

            /** 订单金额为0 **/
            if ($order_data['cur_amount'] == '0')
            {
                // 模拟支付流程
                $objPay = kernel::single("ectools_pay");
                $sdf = array(
                    'payment_id' => $objPay->get_payment_id($order_data['order_id']),
                    'order_id' => $order_data['order_id'],
                    'rel_id' => $order_data['order_id'],
                    'op_id' => $order_data['member_id'],
                    'pay_app_id' => $order_data['payinfo']['pay_app_id'],
                    'currency' => $order_data['currency'],
                    'payinfo' => array(
                        'cost_payment' => $order_data['payinfo']['cost_payment'],
                    ),
                    'pay_object' => 'order',
                    'member_id' => $order_data['member_id'],
                    'op_name' => $this->user->user_data['account']['login_name'],
                    'status' => 'ready',
                    'cur_money' => $order_data['cur_amount'],
                    'money' => $order_data['total_amount'],
                );
                $is_payed = $objPay->gopay($sdf, $msg);
                if (!$is_payed){
                    $msg = app::get('b2c')->_('订单自动支付失败！');
                    $this->end(false, $msg, $this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')));
                }
                $obj_pay_lists = kernel::servicelist("order.pay_finish");
                $is_payed = false;
                foreach ($obj_pay_lists as $order_pay_service_object)
                {
                    $is_payed = $order_pay_service_object->order_pay_finish($sdf, 'succ', 'font',$msg);
                }
            }

            //邮件发送
            if($arr_updates) {
                $order->fireEvent('create', $arr_updates, $order_data['member_id']);
            }
            $myself_email = 'order@qifa.ru';
            $messenger_mod = app::get('b2c')->model('member_messenger')
                ->actionSend('orders-create',$arr_updates,null,$myself_email);

            $this->end(true, $this->app->_("订单生成成功！"), $this->gen_url(array('app'=>'b2c','ctl'=>'site_paycenter','act'=>'index','arg0'=>$order_id,'arg1'=>'true')),'',true);
        }
        else
            $this->end(false, $msg, $this->gen_url(array('app'=>'b2c','ctl'=>'site_cart','act'=>'checkout')),true,true);
    }

    function check_b_orders($filter){
        $obj_goods = $this->app->model('business_orders_objects');
        $goods = $obj_goods->getList('*',$filter);
        $status = '0';
        $flg = true;
        foreach($goods as $key => $item){
            if($item['state'] == '1'){
                $status = '2';
            }
            if($item['state'] == '0'){
                $flg = false;
            }
        }
        if($flg){
            $status = '1';
        }
        return $status;
    }

    //检验订单下供应商订单状态
    function check_order($filter){
        $obj_goods = $this->app->model('business_orders_objects');
        $goods = $obj_goods->getList('*',$filter);
        $status = '0';
        $flg = true;
        foreach($goods as $key => $item){
            if($item['state'] == '0'){
                $flg = false;
                break;
            }
        }
        if($flg){
            $status = '1';
            $obj_order = $this->app->model('orders');
            $orders = $obj_order->getRow('*',array('order_id'=>$filter['mainOrder_id']));
            $obj_type = $this->app->model('dlytype');
            $dt_info = $obj_type->dump($orders['shipping_id']);
            if($dt_info['cost_confirm'] == 'false'){
                $status = '2';
            }
            if($orders['styke'] == 'Самовывоз' || $orders['styke'] == '自提')
            {
                $status = '2';
            }
        }

        return $status;
    }

    //检查确认数量与购数量
    function check_item_num($filter){
        $objOrder = $this->app->model('business_orders_objects');
        $order_items = $objOrder->getList('*',$filter);
        foreach($order_items as $key => $item){
            if($item['has_confirm_num'] != $item['quantity']){
                $result = true;
                break;
            }
        }
        return $result;
    }

    function select_payment(){
        if($_POST['payment']['currency']){
            $sdf['cur'] = $_POST['payment']['currency'];
        }
        //预售商品的判断
        if($_POST['prepare']['promotion_type']=='prepare')
        {
            $sdf['no_offline']='true';
        }
        if($_POST['shipping']['shipping_id']){
            $has_cod = app::get('b2c')->model('dlytype')->getList('has_cod',array('dt_id'=>$_POST['shipping']['shipping_id']));
            #$this->pagedata['has_cod'] = $has_cod[0]['has_cod'] =='true' ? 'true' : 'false';
        }
        $obj_payment_select = new ectools_payment_select();
        $currency = app::get('ectools')->model('currency');
        $this->pagedata['currencys'] = $currency->getList('cur_id,cur_code,cur_name');
        $this->pagedata['current_currency'] = $sdf['cur'] ? $sdf['cur'] : '';
        $this->pagedata['app_id'] = 'b2c';//$app_id;
        $this->pagedata['pay_app_id'] = $_POST['payment']['def_pay']['pay_app_id'];
        $this->pagedata['payment_html'] = $obj_payment_select->select_pay_method($this,$sdf);
        echo $this->fetch('site/common/select_payment.html');
        exit;
    }

    function payment_change(){
        $objOrders = $this->app->model('orders');
        $objPay = kernel::single('ectools_pay');
        $objMath = kernel::single('ectools_math');
        $payments = $_POST['payment'];
        $order_id = $_POST['order_id'];
        $currency = $payments['currency'];
        $pay = json_decode($payments['pay_app_id'],true);
        if($pay['pay_app_id'] == -1){
            return true;
        }
        $arrOrders = $objOrders->dump($order_id,'*');
        if ($arrOrders['payinfo']['pay_app_id'] != $pay['pay_app_id'] || $arrOrders['currency'] != $currency)
        {
            $class_name = "";
            $obj_app_plugins = kernel::servicelist("ectools_payment.ectools_mdl_payment_cfgs");
            foreach ($obj_app_plugins as $obj_app)
            {
                $app_class_name = get_class($obj_app);
                $arr_class_name = explode('_', $app_class_name);
                if (isset($arr_class_name[count($arr_class_name)-1]) && $arr_class_name[count($arr_class_name)-1])
                {
                    if ($arr_class_name[count($arr_class_name)-1] == $pay['pay_app_id'])
                    {
                        $pay_app_ins = $obj_app;
                        $class_name = $app_class_name;
                    }
                }
                else
                {
                    if ($app_class_name == $pay['pay_app_id'])
                    {
                        $pay_app_ins = $obj_app;
                        $class_name = $app_class_name;
                    }
                }
            }
            $strPayment = app::get('ectools')->getConf($class_name);
            $arrPayment = unserialize($strPayment);
            $getcur = app::get('ectools')->model('currency')->getcur($currency);
            $arrOrders['currency'] = $getcur['cur_code'];
            $arrOrders['cur_rate'] = $getcur['cur_rate'];
        }

        $cost_payment = $objMath->number_multiple(array($objMath->number_minus(array($objMath->number_minus(array($arrOrders['total_amount'], $arrOrders['payinfo']['cost_payment'])),$arrOrders['payed'])), $arrPayment['setting']['pay_fee']));
        $total_amount = $objMath->number_plus(array($objMath->number_minus(array($arrOrders['total_amount'], $arrOrders['payinfo']['cost_payment'])), $cost_payment));
        $cur_money = $objMath->number_multiple(array($total_amount, $arrOrders['cur_rate']));

        // 更新订单支付信息
        $arr_updates = array(
            'order_id' => $order_id,
            'payinfo' => array(
                'pay_app_id' => $pay['pay_app_id'],
                'cost_payment' => $objMath->number_multiple(array($cost_payment, $arrOrders['cur_rate'])),
            ),
            'currency' => $arrOrders['currency'],
            'cur_rate' => $arrOrders['cur_rate'],
            'total_amount' => $total_amount,
            'cur_amount' => $cur_money,
        );
        $objOrders->save($arr_updates);
    }

    public function dodelete($order_id){
        $arrMember = kernel::single('b2c_user_object')->get_current_member(); //member_id,uname
        $db = kernel::database();
        $transaction_status = $db->beginTransaction();

        $mdl_order = app::get('b2c')->model('orders');
        $sdf_order = $mdl_order->getRow('*', array('order_id'=>$order_id));
        if($sdf_order['member_id'] != $arrMember['member_id'])
        {
            $db->rollback();
            $this->splash('error','',"请勿删除别人的订单",true);
            return;
        }

        if($sdf_order['status'] != 'dead')
        {
            $db->rollback();
            $this->splash('error','',"请勿删除未取消的订单",true);
            return;
        }

        $sdf_order['displayonsite'] = 'false';
        if($mdl_order->save($sdf_order))
        {
            $db->commit($transaction_status);
            // $this->splash('success','',"删除成功",true);
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'index'));
            $this->redirect($url);
            return;
        }else{
            $db->rollback();
            $this->splash('error','',"删除失败",true);
            return;
        }
    }
}

